//
//  SearchResultViewController.m
//  Cook
//
//  Created by 0.0 on 15-4-18.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//

#import "SearchResultViewController.h"
#import "ResultCollectionViewCell.h"
#import "UIScrollView+PullLoad.h"
#import "MyConnection.h"
#import "VegetableMenu.h"
#import "DetailController.h"
#import "MONActivityIndicatorView.h"

#define searchURL @"http://121.41.87.4:80/HandheldKitchen/api/vegetable/tblvegetable!getChooseFood.do"

/// 搜索结果界面
@interface SearchResultViewController () <UICollectionViewDataSource, UICollectionViewDelegate, PullDelegate, MONActivityIndicatorViewDelegate>
{
   
    NSInteger flag;
    
    CGAdapter _myAd;
    
    UIAlertView *_fileAlertView;
}

@property (nonatomic, retain) NSMutableArray *vegetableArray;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UIView *frontView;
@property (nonatomic, retain) NSTimer *netTimer;

@end


@implementation SearchResultViewController

- (void)dealloc
{
    [_array release];
    [_vegetableArray release];
    [_collectionView release];
    [_frontView release];
    [_netTimer release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.array = [NSMutableArray array];
        self.vegetableArray = [NSMutableArray array];
        _myAd = [AdapterModel getCGAdapter];
        flag = 0;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"搜索结果";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self creatBackGround];
    [self createCollectionView];
    [self createInvidate];
}

#pragma mark - 创建小菊花
- (void)createInvidate
{
    self.frontView = [[UIView alloc] initWithFrame:self.view.frame];
    _frontView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5f];
    [self.view addSubview:_frontView];
    [_frontView release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification) name:@"frontView" object:nil];
    
    MONActivityIndicatorView *indicator = [[MONActivityIndicatorView alloc] init];
    indicator.delegate = self;
    indicator.numberOfCircles = 3;
    indicator.radius = 20;
    indicator.internalSpacing = 3;
    indicator.center = _frontView.center;
    
    // 隐藏顶部navigationbar
    self.navigationController.navigationBar.hidden = YES;
    
    [indicator startAnimating];
    [_frontView addSubview:indicator];
    [indicator release];
    
    self.netTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(isHaveFront) userInfo:nil repeats:NO];
}


// 加载成功
- (void)notification
{
    [_netTimer invalidate];
    self.navigationController.navigationBar.hidden = NO;
    [self.frontView removeFromSuperview];
    self.frontView = nil;
    
}

// 判断加载情况
- (void)isHaveFront
{
    if (_frontView != nil) {
        _fileAlertView = [[UIAlertView alloc] initWithTitle:@"加载失败" message:@"是否重新加载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_fileAlertView show];
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) {
        self.navigationController.navigationBar.hidden = NO;
        [self.navigationController popViewControllerAnimated:YES];
    }
    if (buttonIndex == 1) {
        //        [self createIndicator];
        
        //        [self.view removeFromSuperview];
        [self.frontView removeFromSuperview];
        [self viewDidLoad];
    }
    
    
    
    [_fileAlertView dismissWithClickedButtonIndex:0 animated:YES];
    [_fileAlertView release];
    
}

- (void)creatBackGround
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [imageView setImage:[UIImage imageNamed:@"thirdBarBackground.jpg"]];
    [self.view addSubview:imageView];
    [imageView release];
    
}

- (void)createCollectionView
{
    UICollectionViewFlowLayout *myLayout = [[UICollectionViewFlowLayout alloc] init];
    
    myLayout.itemSize = CGSizeMake(self.view.frame.size.width *0.5 - 20, 140 * _myAd.sHeight);
    myLayout.minimumInteritemSpacing = 5.0f;
    myLayout.minimumLineSpacing = 20.0f;
    myLayout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 20);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:myLayout];
    [myLayout release];
    [_collectionView registerClass:[ResultCollectionViewCell class] forCellWithReuseIdentifier:@"resultCell"];
 
    _collectionView.backgroundColor = [UIColor clearColor];
    
    [_collectionView setDelegate:self];
    [_collectionView setDataSource:self];
    
    [_collectionView setPullDelegate:self];
    [_collectionView setCanPullUp:YES];
    [_collectionView setCanPullDown:NO];
    
    [self.view addSubview:_collectionView];
    [_collectionView release];
    // 进行网络请求
    
    [self scrollView:[[[UIScrollView alloc] init] autorelease] loadWithState:PullUpLoadState];

}

- (void)startConnect:(NSDictionary *)dDic
{
    __block SearchResultViewController *my = self;
    __block UICollectionView *conw = self.collectionView;

    [MyConnection connectWithUrl:searchURL parmaters:dDic finishBlock:^(NSData *data) {
        
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dataDic[@"data"];
        if ([array count] != 0) {
            for (NSDictionary *dic in array) {
                VegetableMenu *model = [VegetableMenu vegetableMenuWithVegetable_id:[dic objectForKey:@"vegetable_id"] name:[dic objectForKey:@"name"] fittingRestriction:[dic objectForKey:@"fittingRestriction"] englishName:[dic objectForKey:@"englishName"] imagePathLandscape:[dic objectForKey:@"imagePathLandscape"] clickCount:[dic objectForKey:@"clickCount"] materialVideoPath:[dic objectForKey:@"materialVideoPath"] productionProcessPath:[dic objectForKey:@"productionProcessPath"]];
                [my.vegetableArray addObject:model];
                
            }
            [conw reloadData];
            [conw stopLoadWithState:PullUpLoadState];
            
        }
        else {
            UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有更多的内容了" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [view show];
            [view release];
            [conw setCanPullUp:NO];
        }
    }];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.vegetableArray count];
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ResultCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"resultCell" forIndexPath:indexPath];
    VegetableMenu *model = [self.vegetableArray objectAtIndex:indexPath.row];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    [cell.foodImageView sd_setImageWithURL:[NSURL URLWithString:model.imagePathLandscape] placeholderImage:image];
    [cell.foodNameLabel setText:model.name];
    [cell.clickLabel setText:[NSString stringWithFormat:@"❤️ %@", model.clickCount]];
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_collectionView deselectItemAtIndexPath:indexPath animated:YES];
    DetailController *detail = [[DetailController alloc] init];
    VegetableMenu *veModel = [self.vegetableArray objectAtIndex:indexPath.item];
    detail.vegetableMenuModel.vegetable_id = veModel.vegetable_id;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
//    [self startConnectWithVegetableId:model.vegetableId];
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *my = [[collectionView indexPathsForVisibleItems] firstObject];
    if (indexPath.item == my.item) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"frontView" object:nil];
    }
}

//?vegetable_id=1649&phonetype=2&user_id=&is_traditional=0


- (void)scrollView:(UIScrollView *)scrollView loadWithState:(LoadState)state
{
    flag++;
    NSString *numTag = nil;
    for (NSString *num in self.array) {
        if (numTag == nil) {
            numTag = num;
        }
        else {
            numTag = [NSString stringWithFormat:@"%@, %@", numTag, num];
        }
    }
    
    NSDictionary *dic = @{@"material_id":numTag, @"page":[NSString stringWithFormat:@"%ld", flag], @"pageRecord":@"10", @"phonetype":@"0", @"is_traditional":@"0", @"user_id":@""};
    
    if (state == PullUpLoadState) {
        [self startConnect:dic];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
